<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 商家管理
 */
namespace app\allwin\model;
use think\Model;
use util\Util;
use app\allwin\model\AllwinStore;

class StoreUnion extends Model{
    
    protected $pk    = 'id';
    protected $table = 'ai_allwin_store_union';
        
    //联盟城市
    public function store(){
        return $this->hasOne('AllwinStore','id','store_id');
    }

    /**
     * ######################
     * 联合商家管理
     */
    public static function unionList(int $store_id){
        $rel = self::where(['store_id' => $store_id])->find();
        if(empty($rel->store_union)){
            return false;
        }
        $store_union = json_decode($rel->store_union,true);
        if(empty($store_union)){
            return false;
        }
        $rel = AllwinStore::where(['id' => $store_union,'is_lock' => 0])->field('id,name,img,address,telphone,score,tips,tags,is_top,state_text')->order('sort desc,id desc')->paginate(10)->toArray();
        if(empty($rel['data'])){
            return false;
        }
        $data = $rel['data'];
        foreach ($rel['data'] as $key => $value) {
            $data[$key]['tags'] = explode(',',$value['tags']);
            $data[$key]['img']  = $value['img']."?x-oss-process=style/w100";
        }
        return $data;
    }

    /**
     * 编辑修改联盟店铺
     */
    public static function unionEdit(int $store_id,int $union_id){
        $union   = [];
        $union[] = $union_id;
        $rel = self::where(['store_id' => $store_id])->find();
        $data = [];
        if(empty($rel)){
            $data['store_id']    = $store_id;
            $data['store_union'] = json_encode($union);
            return self::insert($data);
        }else{
            $store_union = json_decode($rel->store_union,true);
            $key = array_flip($store_union);
            if(array_key_exists($union_id,$key)){
                unset($key[$union_id]);
                $store_union = array_flip($key);
                $store = [];
                foreach ($store_union as $value) {
                    $store[] = $value;
                }
                sort($store);
                $data['store_union'] = json_encode($store);
            }else{
                $store_union = Util::unique_array(array_merge($store_union,$union));
                $data['store_union'] = json_encode($store_union);
            }
            return self::where(['store_id' => $store_id])->update($data);
        }
    } 

    /**
     * 删除联合商家
     */
    public static function unionDelete(array $where){
        return self::where($where)->delete();
    }
}